#include "SampleNode.h"
#include "uac_log.h"


RTRockitDemoNode::RTRockitDemoNode()
{


    // this->handle = fopen("/tmp/outBuffer.wav", "wr");

    // this->secondHandle = fopen("/tmp/outBufferSecond.wav", "wr");

    // fseek(this->handle, 0, SEEK_END);


}

RTRockitDemoNode::~RTRockitDemoNode()
{

    if (NULL != this->handle)
    {
        fclose(this->handle);
    }

    if (NULL != this->secondHandle)
    {
        fclose(this->secondHandle);
    }

    // CAEDestroy(cae);

    // this->cae = NULL;
}

RT_RET RTRockitDemoNode::open(RTTaskNodeContext *context)
{
    RT_RET err = RT_OK;
    RtMetaData *meta = context->options();
    // RTNodeDemoCtx *ctx = reinterpret_cast<RTNodeDemoCtx *>(mCtx);
    // if (RT_NULL == ctx) {
    // RT_LOGE("context is NULL, please alloc RTNodeDemoCtx in construct");
    // return RT_ERR_INIT;
    // }
    // check parameters
    INT32 sampleRate = 0;
    if (!meta->findInt32("opt_samaple_rate", &sampleRate))
    {
        RT_LOGE("samplerate not find");
        return RT_ERR_INIT;
    }
    printf("open开始1！");


    printf("open2!");

    //this->process(context);

    //    CAESetListener(cae, 0, CAEIvwCb, NULL);
    //   CAESetListener(cae, 1, CAEAudioCb, NULL);
    //ctx->mSampleRate = sampleRate;
    // the other init steps
    // int CAEInit(struct AiotOS * param);
    return err;
}

// 用于节点创建， 该函数指针将存于RTNodeStub.mCreateObj中
RTTaskNode *createRockitDemoNode()
{
    return new RTRockitDemoNode();
}

/*  // if (NULL != outSrcLength)
    // {
    //     *outSrcLength = srcLength;
    // }*/
RT_RET RTRockitDemoNode::my_process(RTMediaBuffer *in, RTMediaBuffer *out)
{
    UINT8 *data = reinterpret_cast<UINT8 *>(in->getData());
    UINT32 srcOffset = in->getOffset();
    UINT32 srcLength = in->getLength();
    void *inputData = reinterpret_cast<void *>(&data[srcOffset]);
    INT32 eos = 0;
    INT32 error = 0;
    in->getMetaData()->findInt32("opt_av_eos", &eos);
    in->getMetaData()->findInt32("opt_av_err", &error);
    // if input buffer is eos
    /*	if (eos || error) {
	dstFrame->setRange(0, 0);
	if (eos)
	out->getMetaData()->setInt32("opt_av_eos", 1);
	if (error)
	out->getMetaData()->setInt32("opt_av_err", 1);
	return RTfilter_OK;
	}	*/
    // if output buffer is too small, realloc it
    if (out->getSize() < srcLength)
    {
        out->signalBufferRealloc(srcLength);
    }

    // if (NULL == this->handle)
    // {
    //     printf("文件打开失败\n");
    //     return RT_ERR_BAD;
    // }

    // process data, here we copy data in demo

    void *outBuffter = out->getData();

    memcpy(outBuffter, inputData, srcLength);

 //   this->filter(out);

    // set the length of output buffer
    out->setRange(0, srcLength);
    // set parameters to RTMetaData
    out->getMetaData()->setInt32("opt_samaple_rate", 48000);
    out->getMetaData()->setInt32("opt_channel", 8);
    out->getMetaData()->setInt32("opt_format", RT_AUDIO_FMT_PCM_S16);
    // set data left in input buffer, this is no data left in demo
    in->setRange(0, 0);
    // int once_size = 8*1024*sizeof(short);

    // printf("进来了：RTRockitDemoNode::doAIProcess");

    // CAEAudioWrite(cae, (char *)src->getData(),  once_size);

    return RT_OK;
}

// 节点处理函数，将输入的数据处理， 然后输出到下级节点
RT_RET RTRockitDemoNode::filter(RTMediaBuffer *outputBuffer)
{
    int srcLength =  outputBuffer->getLength();

    char* data = (char*)outputBuffer->getData();

    //fwrite(data, sizeof(char), srcLength, this->handle);

    char ncm[6] = "0:730";
    unsigned int len = 64;
    char ncm_out[64];

    size_t caeLength = 1024;

    size_t number = (srcLength / caeLength);

    int res = 0;

    printf("总共 : %d个数据包\n", number);

    printf("数据包总共：%d\n", srcLength);

    size_t tmpLength = 0;

    char split[caeLength];

    // for (size_t i = 0; i < number; i++)
    // {
    //     strncpy(split, (char *)(data + tmpLength), caeLength);

        // 过滤噪音

	//     printf("memory 复制了\n" );
    //     memcpy(data + tmpLength, split, sizeof(char) * caeLength);

    //     tmpLength += caeLength;

    //     memset(split, '\0', caeLength);

	//     printf("CAEAudioWrite result : %d\n", res);
    // }

    //fwrite(data, sizeof(char), srcLength, this->secondHandle);

    return RT_OK;
}

RT_RET RTRockitDemoNode::process(RTTaskNodeContext *context)
{

    RT_RET err = RT_OK;
    RTMediaBuffer *inputBuffer = RT_NULL;
    // get the first buffer in input queue
    inputBuffer = context->inputHeadBuffer();
    if (inputBuffer != RT_NULL)
    {
        printf("1:input:进来否");
        // get a empty out buffer to store the data after process
        // the fun will be blocked by default if no output left
        this->outputBuffer = context->dequeOutputBuffer();
        if (outputBuffer != RT_NULL)
        {
            printf("2:output:进来否");
            err = my_process(inputBuffer, outputBuffer);
            // in no data in input buffer, dequeue it from input queue
            // and release it
            if (inputBuffer->getLength() <= 0)
            {
                inputBuffer = context->dequeInputBuffer();
                inputBuffer->release();
            }
            // if sucess, set output to output queue.
            if (err == RT_OK)
            {
                
                context->queueOutputBuffer(outputBuffer);
            }
            else
            {
                // if fail, release output buffer
                //output->release();
            }
        }
        else
        {
            inputBuffer = context->dequeInputBuffer();
            inputBuffer->release();
        }
    }
    return RT_OK;
}

RT_RET RTRockitDemoNode::close(RTTaskNodeContext *context)
{
    printf("RT_RET RTRockitDemoNode::close\n");
    return RT_OK;
}
